import 'package:flutter/material.dart';
import 'package:ideology/shared/widgets/file_explorer/file_explorer_theme_data.dart';

import '../../../../../shared/widgets/file_explorer/file_explorer.dart';
import '../../../../../shared/widgets/file_explorer/file_explorer_controller.dart';
import '../../../../../shared/widgets/file_explorer/file_node.dart';

/// 资源管理器面板
///
/// 约定：
/// - 当 [roots] 为空或为 `null` 时，显示占位 UI，并提供“Open the project”操作；
/// - 当 [roots] 非空时，渲染 [FileExplorer] 树；
/// - 通过 [controller] 与 [scrollController] 向下透传控制与滚动状态；
/// - 支持外部注入 [theme]、[realPathResolver] 与节点事件回调。
class ExplorerPanel extends StatelessWidget {
  const ExplorerPanel({
    super.key,
    required this.onOpenFolder,
    required this.controller,
    required this.scrollController,
    this.roots,
    this.onNodeSelect,
    this.onNodeOpen,
    this.onNodeDelete,
    this.theme,
    this.realPathResolver,
  });

  /// 触发“打开项目（选择根目录）”的回调。
  final VoidCallback onOpenFolder;

  /// 根节点集合；为空或 `null` 时显示占位 UI。
  final List<FileNode>? roots;

  /// 节点选中回调（单击选择）。
  final void Function(String path, FileNode node)? onNodeSelect;

  /// 节点打开回调（双击或回车等）。
  final void Function(String path, FileNode node)? onNodeOpen;

  /// 节点删除回调（特别用于根节点被删除后，上层做收尾处理）。
  final void Function(String path, FileNode node)? onNodeDelete;

  /// 文件树主题；未提供时使用内置与当前主题色系适配的默认值。
  final FileExplorerThemeData? theme;

  /// 真实路径解析回调。
  ///
  /// 当 [FileNode.fullPath] 为空时，用于将逻辑路径映射为绝对路径。
  final String Function(String logicalPath, FileNode node)? realPathResolver;

  /// 文件树控制器（展开/折叠、刷新、定位等）。
  final FileExplorerController controller;

  /// 外部滚动控制器（保持与其他部件联动，或用于定位）。
  final ScrollController scrollController;

  @override
  Widget build(BuildContext context) {
    final t = Theme.of(context);
    final cs = t.colorScheme;
    final sectionBorder = BorderSide(color: cs.outline.withValues(alpha: 0.08));

    return Container(
      // 与容器表面色相近，弱化背景存在感
      color: t.colorScheme.surfaceContainerHighest.withValues(alpha: 0.18),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 顶部分隔线，区隔与上方工具栏等区域
          Divider(height: 1, thickness: 1, color: sectionBorder.color),

          // 主体区域：根据 roots 渲染占位或文件树
          Expanded(
            child: Builder(
              builder: (_) {
                if (roots == null || roots!.isEmpty) {
                  // 未打开项目 → 占位内容
                  return SingleChildScrollView(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 16,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Text(
                          'The project has not been opened.',
                          style: t.textTheme.bodyMedium,
                        ),
                        const SizedBox(height: 12),
                        FilledButton(
                          onPressed: onOpenFolder,
                          child: const Text('Open the project'),
                        ),
                        const SizedBox(height: 12),
                      ],
                    ),
                  );
                }

                // 已有 roots → 展示文件树
                return FileExplorer(
                  roots: roots!,
                  initiallyExpandedRoots: false,
                  onNodeSelect: onNodeSelect,
                  onNodeOpen: onNodeOpen,
                  onNodeDelete: onNodeDelete,
                  theme: theme ??
                      FileExplorerThemeData(
                        backgroundColor: Colors.transparent,
                        headerBackgroundColor: cs.surface,
                        headerDividerColor: cs.outline.withValues(alpha: 0.35),
                        hoverColor: cs.primary.withValues(alpha: 0.06),
                        selectionColor: cs.primary.withValues(alpha: 0.16),
                        textColor:
                        t.textTheme.bodyMedium?.color ?? Colors.black87,
                        secondaryTextColor: t.textTheme.bodySmall?.color
                            ?.withValues(alpha: 0.8) ??
                            Colors.black54,
                        folderColor: const Color(0xFFFFB74D),
                        fileColorDefault: const Color(0xFF757575),
                        rowHeight: 26,
                        animationDuration: const Duration(milliseconds: 180),
                      ),
                  controller: controller,
                  scrollController: scrollController,
                  realPathResolver: realPathResolver,
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
